#!/bin/bash

# ============================================
# Nginx 一键安装脚本
# 支持 CentOS/RHEL/Anolis OS 和 Ubuntu/Debian
# ============================================

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
    echo_error "请使用 sudo 运行此脚本"
    exit 1
fi

echo_info "============================================"
echo_info "Nginx 一键安装脚本"
echo_info "============================================"
echo ""

# 检测系统类型
if [ -f /etc/redhat-release ]; then
    OS_TYPE="rhel"
    echo_info "检测到 CentOS/RHEL/Anolis OS 系统"
elif [ -f /etc/debian_version ]; then
    OS_TYPE="debian"
    echo_info "检测到 Ubuntu/Debian 系统"
else
    echo_error "未识别的系统类型"
    exit 1
fi

# 检查 Nginx 是否已安装
if command -v nginx &> /dev/null; then
    echo_warn "Nginx 已安装"
    nginx -v
    read -p "是否重新安装？(y/N): " reinstall
    if [[ ! $reinstall =~ ^[Yy]$ ]]; then
        echo_info "退出安装"
        exit 0
    fi
fi

# ============================================
# CentOS/RHEL/Anolis OS 安装
# ============================================
if [ "$OS_TYPE" = "rhel" ]; then
    echo_step "步骤1: 更新系统包（可选）..."
    read -p "是否更新系统包？(y/N): " update
    if [[ $update =~ ^[Yy]$ ]]; then
        if command -v dnf &> /dev/null; then
            dnf update -y
        else
            yum update -y
        fi
    fi
    
    echo_step "步骤2: 安装 Nginx..."
    if command -v dnf &> /dev/null; then
        dnf install -y nginx
    else
        # 尝试安装 EPEL（如果默认仓库没有 Nginx）
        if ! yum list nginx &> /dev/null; then
            echo_warn "默认仓库没有 Nginx，尝试安装 EPEL..."
            yum install -y epel-release
        fi
        yum install -y nginx
    fi
    
    echo_info "✓ Nginx 安装完成"
fi

# ============================================
# Ubuntu/Debian 安装
# ============================================
if [ "$OS_TYPE" = "debian" ]; then
    echo_step "步骤1: 更新包列表..."
    apt-get update
    
    echo_step "步骤2: 安装 Nginx..."
    apt-get install -y nginx
    
    echo_info "✓ Nginx 安装完成"
fi

# ============================================
# 启动和配置服务
# ============================================
echo_step "步骤3: 启动 Nginx 服务..."

# 启动服务
systemctl start nginx

# 设置开机自启
systemctl enable nginx

# 检查状态
if systemctl is-active --quiet nginx; then
    echo_info "✓ Nginx 启动成功"
else
    echo_error "Nginx 启动失败"
    systemctl status nginx --no-pager
    exit 1
fi

# ============================================
# 配置防火墙
# ============================================
echo_step "步骤4: 配置防火墙..."

if command -v firewall-cmd &> /dev/null; then
    # firewalld (CentOS/RHEL)
    echo_info "检测到 firewalld，配置防火墙规则..."
    
    if systemctl is-active --quiet firewalld; then
        firewall-cmd --permanent --add-service=http
        firewall-cmd --permanent --add-service=https
        firewall-cmd --reload
        echo_info "✓ 防火墙规则已添加"
    else
        echo_warn "firewalld 未运行，跳过防火墙配置"
    fi
    
elif command -v ufw &> /dev/null; then
    # ufw (Ubuntu/Debian)
    echo_info "检测到 ufw，配置防火墙规则..."
    
    ufw allow 80/tcp
    ufw allow 443/tcp
    echo_info "✓ 防火墙规则已添加"
    
elif command -v iptables &> /dev/null; then
    # iptables
    echo_info "检测到 iptables，添加防火墙规则..."
    iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    echo_warn "iptables 规则已添加，请记得保存规则"
else
    echo_warn "未检测到防火墙工具，请手动配置防火墙"
fi

# ============================================
# 验证安装
# ============================================
echo_step "步骤5: 验证安装..."

# 检查版本
echo_info "Nginx 版本信息："
nginx -v

# 检查服务状态
echo_info "服务状态："
systemctl status nginx --no-pager | head -n 5

# 检查端口监听
echo_info "端口监听状态："
if netstat -tlnp 2>/dev/null | grep :80; then
    echo_info "✓ 端口 80 正在监听"
elif ss -tlnp 2>/dev/null | grep :80; then
    echo_info "✓ 端口 80 正在监听"
else
    echo_warn "未检测到端口 80 监听"
fi

# 测试本地访问
echo_info "测试本地访问："
if curl -s http://localhost > /dev/null; then
    echo_info "✓ 本地访问测试成功"
else
    echo_warn "本地访问测试失败"
fi

# ============================================
# 显示配置信息
# ============================================
echo_info "============================================"
echo_info "安装完成！"
echo_info "============================================"
echo_info "Nginx 版本: $(nginx -v 2>&1 | cut -d'/' -f2)"
echo_info "配置文件: /etc/nginx/nginx.conf"
if [ "$OS_TYPE" = "rhel" ]; then
    echo_info "站点配置: /etc/nginx/conf.d/"
    echo_info "默认网站: /usr/share/nginx/html/"
elif [ "$OS_TYPE" = "debian" ]; then
    echo_info "站点配置: /etc/nginx/sites-available/"
    echo_info "默认网站: /var/www/html/"
fi
echo_info "日志目录: /var/log/nginx/"
echo_info ""
echo_info "常用命令："
echo_info "  启动: sudo systemctl start nginx"
echo_info "  停止: sudo systemctl stop nginx"
echo_info "  重启: sudo systemctl restart nginx"
echo_info "  重新加载: sudo systemctl reload nginx"
echo_info "  测试配置: sudo nginx -t"
echo_info "  查看状态: sudo systemctl status nginx"
echo_info ""
echo_info "测试访问："
echo_info "  本地: curl http://localhost"
echo_info "  浏览器: http://你的服务器IP"
echo_info "============================================"

